package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

type Response struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Msg  string `json:"msg"`
}

var token = "asdjh1uio23e"

func main() {
	router := gin.Default()
	router.Use(TimeMiddleware)
	api := router.Group("/api")
	routerGroup := api.Group("/userManager")
	routerGroup.Use(m1)
	routerGroup.GET("/users", userListView)
	api.GET("/login", func(c *gin.Context) {
		//panic("手动报错")
		c.JSON(http.StatusOK, Response{0, gin.H{"token": token}, "success"})
	})
	router.Run(":8080")
}

func userListView(c *gin.Context) {
	userList := []User{
		{"小米", 25},
		{"小红", 23},
		{"小民", 28},
		{"小李", 26},
	}
	c.JSON(http.StatusOK, Response{0, userList, "success"})
}

func m1(c *gin.Context) {
	fmt.Println("m1 in")
	if c.GetHeader("token") == token {
		c.Next()
		return
	}
	c.JSON(http.StatusOK, Response{100, nil, "权限校验失败"})
	c.Abort()
	fmt.Println("m1 out")
}

func TimeMiddleware(c *gin.Context) {
	startTime := time.Now()
	c.Next()
	since := time.Since(startTime)
	fmt.Printf("函数%s耗时%d\n", c.HandlerName(), since)
}
